﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GiMessServer.Net;
using GiMessCommons;

namespace GiMessServer
{
    public class GiMessServer
    {
        private NetServer        netServer;
        private NetMsgHandler    msgHandler;

        private DataFieldsReader dataReader;
        private DataFieldsWriter dataWriter;

        public static GiMessServer Instance      { get; private set; }
        //public      NetServer    NetServerInst { get; private set; }

        public GiMessServer()
        {
            Instance = this;
        }

        public void Start()
        {
            netServer  = new NetServer();
            msgHandler = new NetMsgHandler();

            netServer.NewNetMsg        += msgHandler.HandleMsg;
            netServer.ClientDisconnect += msgHandler.UserSignOut;
             
            Work();
        }

        //Nefolositoare????
        public void Work()
        {
            while (true)
            {
                System.Threading.Thread.Sleep(5);
            }
        }

        #region Complex Server messages

        public void UserIM(string data)
        {
            dataReader = new DataFieldsReader(data);

            string toUserName   = dataReader.GetFieldData(Field.MessageUserDest);
            string fromUserName = dataReader.GetFieldData(Field.MessageUserOrigin);
            string message      = dataReader.GetFieldData(Field.MessageText);
            string font         = dataReader.GetFieldData(Field.MessageFont);

            SendIM(toUserName, fromUserName, message, font);
        }

        public void SendIM(string toUserName, string fromUserName, string message, string font)
        {
            try
            {
                dataWriter = new DataFieldsWriter();
                string fullName = Database.GetFullName(fromUserName);

                dataWriter.WriteField(Field.MessageUserOrigin,   fromUserName);
                dataWriter.WriteField(Field.MessageUserDest,     toUserName);
                dataWriter.WriteField(Field.MessageText,         message);
                dataWriter.WriteField(Field.MessageFont,         font);
                dataWriter.WriteField(Field.MessageUserFullName, fullName);

                netServer.SendNetMsg(toUserName, NetServices.SendMessage, dataWriter.GetString());
            }
            catch (UserNotFoundException unfex)
            {
                Loger.LogLine(unfex.Message, Loger.ServerLogLevel.Verbose);
            }
            
        }

        //TODO rescris in SendNetMessage WHO beause SOMEONE changed WHAT
        public void SendNetMessage(string toUserName, NetMsg msg)
        {
            netServer.SendNetMsg(toUserName, msg);
        }
        #endregion
    }
}
